import type { TreeOption } from 'naive-ui'
import type { ProTableProps } from '../../typing.ts'

/**
 * @ClassName: setting-column
 * @Description: // 数据状态管理
 * @Author: Ellwood
 * @CreateDate: 2024/2/29 - 7:35
 * @Version: V1.0.0
 */
export function useSettingColumn(props: ProTableProps) {
  const treeData = ref<TreeOption[]>([])
  const checkedKeys = ref<string[]>([])
  const allCheckedKeys = ref<string[]>([])

  const init = () => {
    treeData.value = []
    allCheckedKeys.value = []
    checkedKeys.value = []

    const columns = props.columns
    for (const column of columns) {
      const item: TreeOption = {
        label: column.title,
        key: column.key,
      }
      checkedKeys.value.push(column.key as string)
      treeData.value.push(item)
    }
    allCheckedKeys.value = checkedKeys.value.slice()
  }

  // 监听props.columns的变化
  watch(() => props.columns, () => {
    init()
  }, { immediate: true })

  const isAllChecked = computed(() => {
    return checkedKeys.value.length === allCheckedKeys.value.length
  })

  const indeterminate = computed(() => {
    return checkedKeys.value.length > 0 && checkedKeys.value.length < allCheckedKeys.value.length
  })

  const handleCheckedKeys = (keys: string[]) => {
    checkedKeys.value = keys
  }
  const handleCheckedAll = (checked: string[]) => {
    if (checked)
      checkedKeys.value = allCheckedKeys.value.slice()
    else
      checkedKeys.value = []
  }

  const cols = computed(() => {
    return props?.columns?.filter(col => checkedKeys.value.includes(col.key as string))
  })

  return {
    treeData,
    checkedKeys,
    isAllChecked,
    indeterminate,
    handleCheckedKeys,
    handleCheckedAll,
    init,
    cols,
  }
}
